package org.example.redis.controller;

import org.example.redis.utils.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/seckill")
public class SecKillController {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @PostMapping("/buy")
    public JsonResult buy(@RequestParam("goodsId") int goodsId, @RequestParam("memberId") int memberId){
        //1.判读库存
        String goodsStockKey = "goods-stock:"+goodsId;
        String stock = stringRedisTemplate.opsForValue().get(goodsStockKey);
        System.out.println(stock);
        if (stock == null || Integer.parseInt(stock) == 0) {
            return JsonResult.failed("已经抢完");
        }
        //2.把会员id放到队列
        Long res = stringRedisTemplate.opsForList().leftPush("list-goods:" + goodsId, String.valueOf(memberId));
        //3.扣减库存
        if (res != null) {
            stringRedisTemplate.opsForValue().decrement(goodsStockKey,1);
        }
        return JsonResult.success("ok",null);
    }
    //下单
    @PostMapping("creatOrder")
    public JsonResult createOrder(@RequestParam("goodsId") int goodsId) {
        String key = "list-goods:" + goodsId;
        String res = stringRedisTemplate.opsForList().rightPop(key);
        System.out.println(res);
        //生成订单 rabbitmq,kafka
        return JsonResult.success("ok",null);
    }
}

